import { MessageBox } from 'element-ui';
import { Message } from 'element-ui'
export function parseTime(time, cFormat) {
    if (arguments.length === 0) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if (('' + time).length === 10) time = parseInt(time) * 1000
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str
}
export function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}

export function timeDiff(d1) {
    if (!!d1) {
        var dateBegin = new Date(d1.replace(/-/g, '/')) // 将-转化为/，使用new Date
        var dateEnd = new Date() // 获取当前时间
        var dateDiff = dateEnd.getTime() - dateBegin.getTime() // 时间差的毫秒数
        var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)) // 计算出相差天数
        var leave1 = dateDiff % (24 * 3600 * 1000) // 计算天数后剩余的毫秒数
        var hours = Math.floor(leave1 / (3600 * 1000)) // 计算出小时数
            // 计算相差分钟数
        var leave2 = leave1 % (3600 * 1000) // 计算小时数后剩余的毫秒数
        var minutes = Math.floor(leave2 / (60 * 1000)) // 计算相差分钟数
            // 计算相差秒数
        var leave3 = leave2 % (60 * 1000) // 计算分钟数后剩余的毫秒数
        var seconds = Math.round(leave3 / 1000)
            // console.log(" 相差 "+dayDiff+"天 "+hours+"小时 "+minutes+" 分钟"+seconds+" 秒")
            // console.log("计算出相差天数: "+dayDiff);
        if (dayDiff >= 3) {
            return true
        } else {
            return false
        }
    }
}
/**
 * 获取浏览器可视宽高 兼容 +
 */
export const getBrowserInterfaceSize = () => {
        let pageWidth = window.innerWidth
        let pageHeight = window.innerHeight

        if (typeof pageWidth !== 'number') {
            // 在标准模式下面
            if (document.compatMode === 'CSS1Compat') {
                pageWidth = document.documentElement.clientWidth
                pageHeight = document.documentElement.clientHeight
            } else {
                pageWidth = document.body.clientWidth
                pageHeight = document.body.clientHeight
            }
        }
        return {
            pageWidth: pageWidth,
            pageHeight: pageHeight
        }
    }
    /*
     *获取地址中的参数列表
     */
export const getUrlVars = url => {
        if (!url) {
            url = window.location.href;
        };
        var vars = [],
            hash;
        var hashes;
        hashes = url.slice(url.indexOf('?') + 1).split(/[&#]/);
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            try {
                vars[hash[0]] = decodeURIComponent(hash[1]);
            } catch (e) {}
        }
        return vars;
    }
    //封装message组件
export const message = (options = { showClose: true, message: '网络出错啦...', type: 'success', duration: 2000 }) => {
        return Message(options)
    }
    /*
     *获取地址中的指定参数值
     */
export const getUrlParam = (name, url) => {
        return getUrlVars(url)[name];
    }
    /**
     * 将数值四舍五入(保留2位小数)后格式化成金额形式
     *
     * @param num 数值(Number或者String)
     * @return 金额格式的字符串,如'1,234,567.45'
     * @type String
     */
export const formatCurrency = (number, places, symbol = '', thousand = ',', decimal = '.') => {
        number = number || 0;
        places = !isNaN(places = Math.abs(places)) ? places : 2;
        symbol = symbol !== undefined ? symbol : "$";
        thousand = thousand || ",";
        decimal = decimal || ".";
        var negative = number < 0 ? "-" : "",
            i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
            j = (j = i.length) > 3 ? j % 3 : 0;
        return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
    }
    //格式化银行卡
export const cardFormat = (bankCard) => {
        return bankCard
            .replace(/\s/g, "")
            .replace(/(\d{4})\d+(\d{4})$/, "●●●● ●●●● ●●●● $2");
    }
    // 路由切换
export const routerPush = (that, url, query, params) => {
        that.$router.push({ path: url, params: params, query: query });
    }
    /**
     * 数字金额大写转换(可以处理整数,小数,负数)
     *
     * @param n 数值(Number或者String)
     * @return
     * @type String
     */
export const digitUppercase = (n) => {
        var fraction = ['角', '分'];
        var digit = [
            '零', '壹', '贰', '叁', '肆',
            '伍', '陆', '柒', '捌', '玖'
        ];
        var unit = [
            ['元', '万', '亿'],
            ['', '拾', '佰', '仟']
        ];
        var head = n < 0 ? '欠' : '';
        n = Math.abs(n);
        var s = '';
        for (var i = 0; i < fraction.length; i++) {
            s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
        }
        s = s || '整';
        n = Math.floor(n);
        for (var i = 0; i < unit[0].length && n > 0; i++) {
            var p = '';
            for (var j = 0; j < unit[1].length && n > 0; j++) {
                p = digit[n % 10] + unit[1][j] + p;
                n = Math.floor(n / 10);
            }
            s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
        }
        return head + s.replace(/(零.)*零元/, '元')
            .replace(/(零.)+/g, '零')
            .replace(/^整$/, '零元整');
    }
    /**
     * js浮点型数字运算的溢出bug处理
     * @param {数字1} arg1 
     * @param {数字2} arg2 
     * @param {运算符} operators 
     */
export const operator = (arg1, arg2, operators) => {
        if (operators == "+") {
            var r1, r2, m, c;
            try {
                r1 = arg1.toString().split(".")[1].length;
            } catch (e) {
                r1 = 0;
            }
            try {
                r2 = arg2.toString().split(".")[1].length;
            } catch (e) {
                r2 = 0;
            }
            c = Math.abs(r1 - r2);
            m = Math.pow(10, Math.max(r1, r2));
            if (c > 0) {
                var cm = Math.pow(10, c);
                if (r1 > r2) {
                    arg1 = Number(arg1.toString().replace(".", ""));
                    arg2 = Number(arg2.toString().replace(".", "")) * cm;
                } else {
                    arg1 = Number(arg1.toString().replace(".", "")) * cm;
                    arg2 = Number(arg2.toString().replace(".", ""));
                }
            } else {
                arg1 = Number(arg1.toString().replace(".", ""));
                arg2 = Number(arg2.toString().replace(".", ""));
            }
            return (arg1 + arg2) / m;
        } else if (operators == "-") {
            var r1, r2, m, n;
            try {
                r1 = arg1.toString().split(".")[1].length;
            } catch (e) {
                r1 = 0;
            }
            try {
                r2 = arg2.toString().split(".")[1].length;
            } catch (e) {
                r2 = 0;
            }
            m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
            n = (r1 >= r2) ? r1 : r2;
            return ((arg1 * m - arg2 * m) / m).toFixed(n);
        } else if (operators == "*") {
            var m = 0,
                s1 = arg1.toString(),
                s2 = arg2.toString();
            try {
                m += s1.split(".")[1].length;
            } catch (e) {}
            try {
                m += s2.split(".")[1].length;
            } catch (e) {}
            return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
        } else if (operators == "/") {
            var t1 = 0,
                t2 = 0,
                r1, r2;
            try {
                t1 = arg1.toString().split(".")[1].length;
            } catch (e) {}
            try {
                t2 = arg2.toString().split(".")[1].length;
            } catch (e) {}
            r1 = Number(arg1.toString().replace(".", ""));
            r2 = Number(arg2.toString().replace(".", ""));
            return (r1 / r2) * Math.pow(10, t2 - t1);
        }
    }
    //验证上传文件大小和类型

/**
 * 
 * @param {this} value_ [获取input对象，一般为this]
 * @param {[number]} size_ [文件限制的大小，单位为kb]
 * @param {[string]} type_ [文件类型，当前支持image和office]
 * @param {[function]} callback [验证通过的回调]
 */

export const fileValid = (value_, size_, type_, callback) => {
    var file = value_.files[0]
    var fileSize = (file.size / 1024).toFixed(0)
    var fileType = value_.value.substring(value_.value.lastIndexOf("."))

    if (fileSize > size_) {
        alert('文件过大')
        return false
    }

    switch (type_) {
        case 'video':
            if (!fileType.match(/.mp4|.avi/i)) {
                alert('请上传视频')
                return false;
            }
            break;
        case 'image':
            if (!fileType.match(/.jpg|.jpeg|.gif|.png|.bmp/i)) {
                alert('请上传图片')
                return false;
            }
            break;
        case 'office':
            if (!fileType.match(/.doc|.docx|.xls|.xlsx|.ppt|.pptx/i)) {
                alert('请上传word、excel或ppt文件')
                return false;
            }
            break;
        default:
            console.error('type_参数设置不正确！')
            return false;
            break;
    }

    callback()
}